﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESF.General;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

#endregion


namespace ESF.FileProcessing
{
	public class CombinePDFHelper : BaseTaskManager
	{
		#region Constructor

		public CombinePDFHelper(ProcessHelper.ReportProgressDelegate pdelReportProgressDelegate = null) 
			: base (pdelReportProgressDelegate) {}

		#endregion


		#region Funciones

		public void CombinePDFs (string pNewFileName, params string[] pFileNames)
		{
			int pageOffset = 0;
			int pageAdvance = 0;
			int pageTotalCount = 0;

			PdfReader reader = null;


			if (DataHelper.IsEmpty(pFileNames) || pFileNames.Length < 2)
			{
				throw new GenericInfoException("Debe proporcionar al menos dos archivos para combinar");
			}

			FileHelper.Delete(pNewFileName);


			#region Detectar Total para Avance

			foreach (string currentFileName in pFileNames)
			{
				try
				{
					pageTotalCount += PDFHelper.GetItemCount(currentFileName);
				}
				catch (Exception pEx)
				{
					throw new GenericInfoException(string.Format("El archivo {0} no es legible: {1}", currentFileName, pEx.Message), pEx);
				}
			}
		
			#endregion


			try
			{
				Start (pageTotalCount);


				// step 1: creation of a document-object
				using (Document document = new Document()) //reader.GetPageSizeWithRotation(1));
				{
					// step 2: we create a writer that listens to the document
					using (PdfCopy writer = new PdfCopy(document, new FileStream(pNewFileName, FileMode.Create)))
					{
						// step 3: we open the document
						document.Open();


						foreach (string f in pFileNames)
						{
							try
							{
								// we create a reader for a certain document
								reader = new PdfReader(f);
								reader.ConsolidateNamedDestinations();
								// we retrieve the total number of pages
								int n = reader.NumberOfPages;
								pageOffset += n;


								// step 4: we add content
								for (int i = 0; i < n; )
								{
									++i;
									if (writer != null)
									{
										PdfImportedPage page = writer.GetImportedPage(reader, i);
										writer.AddPage(page);

										IncrementReadyCount ();

										pageAdvance++;

										ReportProgress();
									}
								}

								PRAcroForm form = reader.AcroForm;
								if (form != null && writer != null)
								{
									writer.CopyAcroForm(reader);
								}
							}
							finally 
							{
								if (reader != null)
								{
									reader.Close ();
								}
							}
						}
					}
				}
			}
			finally
			{
				Stop ();
			}
		}

		#endregion
	}
}
